from sqlalchemy.orm import Session, joinedload

from core import models, schemas
from core.models import User, Department


# 用户
def user_detail_by_username(db: Session, username: str):
    return db.query(models.User).options(joinedload(models.User.department)).filter(
        models.User.username == username).first()


def user_detail_by_id(db: Session, user_id: int):
    return db.query(models.User).options(joinedload(models.User.department)).filter(
        models.User.user_id == user_id).first()


def user_save(db: Session, user: schemas.UserCreate):
    db_user = models.User(username=user.username, password=user.password, phone=user.phone, address=user.address,
                          department_id=user.department_id)
    db.add(db_user)
    db.commit()
    db.refresh(db_user)
    return db_user


def user_change_address0(db: Session, db_user: User, address: str):
    db_user.address = address
    db.commit()
    db.refresh(db_user)


# 部门
def get_department(db: Session, department_id: int):
    return db.query(Department).filter(Department.department_id == department_id).first()


def create_department(db: Session, department: schemas.DepartmentSchema):
    db_department = Department(department_id=department.department_id, department_name=department.department_name)
    db.add(db_department)
    db.commit()
    db.refresh(db_department)
    return db_department.to_dict()


def update_department(db: Session, department_id: int, department: Department):
    db_department = get_department(db, department_id)
    if db_department is None:
        return None
    for key, value in department.dict().items():
        setattr(db_department, key, value)
    db.commit()
    return db_department.to_dict()


def delete_department(db: Session, department_id: int):
    db_department = get_department(db, department_id)
    if db_department is None:
        return None
    db.delete(db_department)
    db.commit()
    return db_department.to_dict()
